package com.jixi.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jixi.common.exception.NullFailedException;
import com.jixi.common.exception.PowerFailedException;
import com.jixi.common.result.PageResult;
import com.jixi.common.result.Result;
import com.jixi.mapper.AccountMapper;
import com.jixi.mapper.CompanyMapper;
import com.jixi.mapper.EducationMapper;
import com.jixi.mapper.SchoolMapper;
import com.jixi.pojo.dto.AccountAddDto;
import com.jixi.pojo.entity.Account;
import com.jixi.pojo.entity.Company;
import com.jixi.pojo.entity.Education;
import com.jixi.pojo.entity.School;
import com.jixi.pojo.vo.AccountListVO;
import com.jixi.service.AccountService;
import com.jixi.service.CompanyService;
import com.jixi.service.SchoolService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService {
	
	@Autowired
	private EducationMapper educationMapper;
	
	@Autowired
	private AccountMapper accountMapper;
	
	@Autowired
	private CompanyMapper companyMapper;
	
	@Autowired
	private SchoolMapper schoolMapper;
	
	/**
	 * 新增账户
	 *
	 * @param accountAddDto 新增账户信息
	 * @return 新增结果
	 */
	@Override
	public Result addAcount(AccountAddDto accountAddDto) {
		//先查登录的账号的权限
		Long loginEducationId = StpUtil.getLoginIdAsLong();
		//构造查询
		LambdaQueryWrapper<Education> queryWrapper = new LambdaQueryWrapper<>();
		//以id作为查询依据
		queryWrapper.eq(Education::getEducationId, loginEducationId);
		//获取实例
		Education loginEducation = educationMapper.selectOne(queryWrapper);
		//判断权限
		if (loginEducation.getEducationPower() != 1) {
			throw new PowerFailedException("权限不足");
		}
		Account account = new Account();
		BeanUtils.copyProperties(accountAddDto, account);
		account.setIsDeleted(0);
		log.info("新增信息：{}", account);
		accountMapper.insert(account);
		return Result.success("新增成功");
	}
	
	/**
	 * 账户列表
	 *
	 * @param pageNum         页码
	 * @param pageSize        每页数量
	 * @param accountType     银行类型
	 * @param accountBankId   账户卡号
	 * @param accountNickname 账户昵称
	 * @param status          状态
	 * @return 账户列表
	 */
	@Override
	public Result<PageResult> accountPage(
			Integer pageNum,
			Integer pageSize,
			String accountType,
			String accountBankId,
			String accountNickname,
			Integer status,
			Long educationId
	) {
		//分页构造器
		Page<Account> pageInfo = new Page<>(pageNum, pageSize);
		//条件构造器
		LambdaQueryWrapper<Account> queryWrapper = new LambdaQueryWrapper<>();
		//只查未删除的
		queryWrapper.eq(Account::getIsDeleted, 0);
		//添加可能有的过滤条件
		queryWrapper.like(accountType != null && !accountType.trim().isEmpty(), Account::getAccountType, accountType);
		queryWrapper.like(accountBankId != null && !accountBankId.trim().isEmpty(), Account::getAccountBankId, accountBankId);
		queryWrapper.like(accountNickname != null && !accountNickname.trim().isEmpty(), Account::getAccountNickname, accountNickname);
		queryWrapper.eq(status != null, Account::getStatus, status);
		queryWrapper.eq(educationId != null, Account::getEducationId, educationId);
		//执行分页查询
		accountMapper.selectPage(pageInfo, queryWrapper);
		
		//处理名字信息
		List<AccountListVO> AccountList = pageInfo.getRecords().stream()
				.map(account -> {
					AccountListVO vo = new AccountListVO();
					BeanUtils.copyProperties(account, vo); //使用Spring的Bean工具类复制属性
					
					Long educationId1 = vo.getEducationId();
					Education education = educationMapper.selectById(educationId1);
					if (education == null || education.getIsDeleted() == 1) {
						vo.setEducationNickname("该教育局账号不存在");
					} else if (education.getStatus() == 0) {
						vo.setEducationNickname(education.getEducationNickname() + "（该教育局账号已停用）");
					} else {
						vo.setEducationNickname(education.getEducationNickname());
					}
					
					return vo;
				}).collect(Collectors.toList());
		
		//处理分页信息
		PageResult pageResult = new PageResult(pageInfo.getTotal(), AccountList);
		return Result.success(pageResult);
	}
	
	/**
	 * 账户详情
	 *
	 * @param accountId 账户id
	 * @return 账户详情
	 */
	@Override
	public Account getAcountInfo(Long accountId) {
		return accountMapper.selectById(accountId);
	}
	
	/**
	 * 账户修改
	 *
	 * @param accountId       账户id
	 * @param accountNickname 账户昵称
	 * @param remark          备注
	 * @param status          状态
	 * @param educationId     教育局id
	 * @return 修改结果
	 */
	@Override
	public Result updateAccountById(Long accountId, String accountNickname, String remark, Integer status, Long educationId) {
		//先查登录的账号的权限
		Long loginEducationId = StpUtil.getLoginIdAsLong();
		//构造查询
		LambdaQueryWrapper<Education> queryWrapper = new LambdaQueryWrapper<>();
		//以id作为查询依据
		queryWrapper.eq(Education::getEducationId, loginEducationId);
		//获取实例
		Education loginEducation = educationMapper.selectOne(queryWrapper);
		
		//判断权限
		if (loginEducation.getEducationPower() != 1) {
			throw new PowerFailedException("权限不足");
		}
		
		//先判断教育局id是否存在
		LambdaQueryWrapper<Education> queryWrapper2 = new LambdaQueryWrapper<>();
		queryWrapper2.eq(Education::getEducationId, educationId);
		queryWrapper2.eq(Education::getIsDeleted, 0);
		Education education = educationMapper.selectOne(queryWrapper2);
		if (education == null) {
			return Result.fail("该教育局账号不存在");
		}
		
		LambdaQueryWrapper<Account> queryWrapper1 = new LambdaQueryWrapper<>();
		//只查未删除的
		queryWrapper1.eq(Account::getIsDeleted, 0);
		queryWrapper1.eq(Account::getAccountId, accountId);
		Account account = accountMapper.selectOne(queryWrapper1);
		account.setAccountNickname(accountNickname);
		account.setRemark(remark);
		account.setStatus(status);
		account.setEducationId(educationId);
		account.setUpdateTime(DateTime.now());
		accountMapper.updateById(account);
		return Result.success("修改成功");
	}
	
	/**
	 * 账户状态修改
	 *
	 * @param accountId 账户id
	 * @param status    状态
	 * @return 修改结果
	 */
	@Override
	public Result updateAccountStatus(Long accountId, Integer status) {
		//先查登录的账号的权限
		Long loginEducationId = StpUtil.getLoginIdAsLong();
		//构造查询
		LambdaQueryWrapper<Education> queryWrapper = new LambdaQueryWrapper<>();
		//以id作为查询依据
		queryWrapper.eq(Education::getEducationId, loginEducationId);
		//获取实例
		Education loginEducation = educationMapper.selectOne(queryWrapper);
		//判断权限
		if (loginEducation.getEducationPower() != 1) {
			throw new PowerFailedException("权限不足");
		}
		
		//先查是否存在餐饮公司或学校使用这张卡
		LambdaQueryWrapper<Company> queryWrapperCompany = new LambdaQueryWrapper<>();
		queryWrapperCompany.eq(Company::getAccountId, accountId);
		queryWrapperCompany.eq(Company::getIsDeleted, 0);
		Long countCompany = companyMapper.selectCount(queryWrapperCompany);
		
		LambdaQueryWrapper<School> queryWrapperSchool = new LambdaQueryWrapper<>();
		queryWrapperSchool.eq(School::getAccountId, accountId);
		queryWrapperSchool.eq(School::getIsDeleted, 0);
		Long countSchool = schoolMapper.selectCount(queryWrapperSchool);
		
		if (countCompany > 0 || countSchool > 0) {
			return Result.fail("该账户正在被 " + countSchool + " 个学校和 " + countCompany + " 个餐饮公司使用，无法停用。");
		}
		
		//修改状态
		if (status != 1 && status != 0) {
			throw new NullFailedException("状态值有误");
		}
		//执行修改
		LambdaQueryWrapper<Account> queryWrapper1 = new LambdaQueryWrapper<>();
		//只查未删除的
		queryWrapper1.eq(Account::getIsDeleted, 0);
		queryWrapper1.eq(Account::getAccountId, accountId);
		Account account = accountMapper.selectOne(queryWrapper1);
		account.setStatus(status);
		account.setUpdateTime(DateTime.now());
		accountMapper.updateById(account);
		return Result.success("状态修改成功");
	}
	
	/**
	 * 账户删除
	 *
	 * @param accountId 账户id
	 * @return 删除结果
	 */
	@Override
	public Result deleteAccountById(Long accountId) {
		
		//先查登录的账号的权限
		Long loginEducationId = StpUtil.getLoginIdAsLong();
		//构造查询
		LambdaQueryWrapper<Education> queryWrapper = new LambdaQueryWrapper<>();
		//以id作为查询依据
		queryWrapper.eq(Education::getEducationId, loginEducationId);
		//获取实例
		Education loginEducation = educationMapper.selectOne(queryWrapper);
		//判断权限
		if (loginEducation.getEducationPower() != 1) {
			throw new PowerFailedException("权限不足");
		}
		//假删除
		LambdaQueryWrapper<Account> queryWrapper1 = new LambdaQueryWrapper<>();
		//只查未删除的
		queryWrapper1.eq(Account::getIsDeleted, 0);
		queryWrapper1.eq(Account::getAccountId, accountId);
		Account account = accountMapper.selectOne(queryWrapper1);
		account.setIsDeleted(1);
		account.setAccountBankId("accountId: " + account.getAccountId() + "已删除, 原卡号: " + account.getAccountBankId());
		account.setUpdateTime(DateTime.now());
		accountMapper.updateById(account);
		return Result.success("删除成功");
	}
}
